package com.inventive.jmscache.server.hazelcast;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IQueue;
import com.inventive.jmscache.server.JmsCacheException;
import com.inventive.jmscache.server.JmsCacheMessage;
import com.inventive.jmscache.server.BackendQueue;
import sun.misc.resources.Messages;

import javax.jms.JMSException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Grant Little <grant.little@coreservices.com.au>
 */
public class HazelcastCachedQueue implements BackendQueue {

    private String name;

    public HazelcastCachedQueue(String name) {
        this.name = name;
    }

    public void put(JmsCacheMessage message) {
        try {
            String messageId = message.getJMSMessageID();
            if (messageId == null) {
                messageId = UUID.randomUUID().toString();
            }
            Hazelcast.getMap(name).put(messageId, message);
            Hazelcast.getQueue(name).put(message);
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new JmsCacheException(e);
        }
    }

    public JmsCacheMessage poll() {
        IQueue<String> queue = Hazelcast.getQueue(name);

        String messageId = queue.poll();
        IMap<String, JmsCacheMessage> messages = Hazelcast.getMap(name);
        JmsCacheMessage message = messages.get(messageId);
        messages.remove(messageId);
        return message;

    }

    public JmsCacheMessage poll(long timeoutMillis) {
        IQueue<JmsCacheMessage> queue = Hazelcast.getQueue(name);
        try {
            return queue.poll(timeoutMillis, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new JmsCacheException(e);
        }
    }

}
